#!/bin/bash
#
# Author: Gary Locke
#
# Description:
#    Apache vhost finder
#
# Usage:
#    ./script.sh domain /path/to/client/conf

if [[ "$(whoami)" != "root" ]];then
    echo -ne "\nThis script must be run as root.\n"; exit 1
fi

RED="\033[1;31m"
GREEN="\033[1;32m"
COLOR_RESET="\033[0m"
BOLD=`tput bold`
NORMAL=`tput sgr0`

httpd_root="$(httpd -V|awk -F'"' '/HTTPD_ROOT/ {print $2}')"
server_config_file="$(httpd -V|awk -F'"' '/SERVER_CONFIG_FILE/ {print $2}')"
httpd_conf="$(printf "$httpd_root/$server_config_file")"

domain=$1
if [[ -z "$domain" ]];then
    read -e -p "Enter search string (e.g. domain.com): " domain
fi

client_conf=$2
if [[ -z "$client_conf" ]];then
    echo -ne "\n${BOLD}No client configuration specified!\n"
    echo -ne "Here are the included configs from $httpd_conf...${NORMAL}\n\n"
    egrep ^Include $httpd_conf;echo
    read -e -p "Enter path to virtual host config: " client_conf
fi

if egrep -i "^sslengine.*on" $client_conf >/dev/null 2>&1;then
    echo -ne "\n${BOLD}SSL detected, checking for SSL-enabled virtual host for $domain...${NORMAL}\n"
    ssl_results="$(sed -n '/^<IfDefine.*SSL/,/^<\/IfDefine/{:a;N;$!ba};s/\n/jqfLRuCZiHLT/g;s/IfDefine>/&\n/g;s/^$//g;p' $client_conf|\
        awk "/[Ss][Ss][Ll]/ && /$domain/"|\
        sed 's/jqfLRuCZiHLT/\n/g'|\
        egrep -v ^$)"
    if [[ ! -z "$ssl_results" ]];then
        echo -ne "\n$ssl_results\n\n";exit
    fi
fi

echo -ne "${BOLD}No SSL virtual hosts found for $domain.${NORMAL}\n"

sed -n '/^<Vi/,/^<\/Vi/{:a;N;$!ba};s/\n/jqfLRuCZiHLT/g;s/Host>/&\n/g;s/^$//g;p' $client_conf|\
    grep $domain|\
    sed 's/jqfLRuCZiHLT/\n/g'|\
    egrep -iv '(ifdefine|^$)'

echo;exit
